package site.assad.web;

import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import org.springframework.web.servlet.view.document.AbstractPdfView;
import com.lowagie.text.pdf.PdfWriter;
import site.assad.domain.User;

import javax.management.RuntimeMBeanException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * Author: Al-assad 余林颖
 * E-mail: yulinying_1994@outlook.com
 * Date: 2018/1/8 15:09
 * Description: PDF 视图的 bean
 */
public class UserListPDFView extends AbstractPdfView{

    @Override
    protected void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setHeader("Content-Disposition","inline;filename=" + new String("用户列表".getBytes(),"iso8859-1"));
        List<User> userList =(List<User>) model.get("userList");

        //创建表格，并设置表格格式
        Table table = new Table(3);
        table.setWidth(80);         //设置表格宽度
        table.setBorder(1);         //设置表格边框
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);  //设置对齐格式
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE);

        //设置中文字体
        BaseFont cnBaseFont = BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H",false);
        Font cnFont = new Font(cnBaseFont,10,Font.NORMAL, Color.BLUE);

        //填充表头,中文字符需要使用转换器构造Cell，否则会产生乱码
        table.addCell(buildFontCell("账号",cnFont));
        table.addCell(buildFontCell("名称",cnFont));
        table.addCell(buildFontCell("生日",cnFont));
        //填充表格数据
        for(User user : userList){
            table.addCell(user.getUserId()+"");  //英文字符直接添加
            table.addCell(buildFontCell(user.getUserName(),cnFont));
            table.addCell(new SimpleDateFormat("yyyy-MM-dd").format(user.getBirthday()));
        }

    }

    private Cell buildFontCell(String content,Font font) throws RuntimeException{
        try {
            return new Cell(new Phrase(content,font));
        } catch (BadElementException e) {
            throw new RuntimeException(e);
        }
    }

}
